package com.example.universita.esami;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;

import com.androidplot.Plot;
import com.androidplot.series.XYSeries;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class StatisticActivity extends Activity  {

    protected static final int ID_FINESTRA = 0;
    Dialog ModelDialog;
    final int maxVotoLaurea = 12, minVotoLaurea = 3;
    DBDataUniversity db;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistic);
        
        float result_ponderate=0, result=0;

        db = new DBDataUniversity(this);

        db.open();
        
        // GESTIONE NUMERO ESAMI SUPERATI
        TextView numero_esami = (TextView)findViewById(R.id.textView6);
        int n_tot_esami = db.numTotalExams();
        numero_esami.setText(db.numberAllExamsOk()+" "+getString(R.string.st_totale)+" " + n_tot_esami+" ");
        
        ProgressBar p1= (ProgressBar)findViewById(R.id.progressBar3);
        p1.setMax(n_tot_esami);
        p1.setProgress((int) db.numberAllExamsOk());
        
        // GESTIONE CREDITI RAGGIUNTI
        TextView numero_crediti = (TextView)findViewById(R.id.textView8);
        int n_tot_crediti = db.numTotalCredits();
        numero_crediti.setText(db.numberAllCreditsOk()+" "+getString(R.string.st_totale)+" " + n_tot_crediti+" ");
        
        ProgressBar p2= (ProgressBar)findViewById(R.id.progressBar4);
        p2.setMax(n_tot_crediti);
        p2.setProgress((int) db.numberAllCreditsOk());
        
        // GESTIONE MEDIA ARTIMETICA
        TextView media_aritmetica = (TextView)findViewById(R.id.textView2);
        int n_esami = db.numberOkExams();
        if(n_esami > 0){
        	result = (float)db.sumVote() / n_esami;
        	result =(float)Math.round(result*100) / 100;
        	media_aritmetica.setText(result+" / 30.00 ");
        }
        else
        	media_aritmetica.setText("0.00 / 30.00 ");
        
        ProgressBar p4= (ProgressBar)findViewById(R.id.progressBar2);
        p4.setMax(12);
        p4.setProgress((int)result - 18);
        
        // GESTIONE MEDIA PONDERATA
        TextView media_ponderata = (TextView)findViewById(R.id.textView4);
        int n_crediti = db.numberCredits();
        if(n_crediti > 0){
        	result_ponderate = (float)db.sumVotePonderate() / n_crediti;
        	result_ponderate =(float)Math.round(result_ponderate*100) / 100;
        	media_ponderata.setText(result_ponderate+" / 30.00 ");
        }
        else
        	media_ponderata.setText("0.00 / 30.00 ");
        
        ProgressBar p3= (ProgressBar)findViewById(R.id.progressBar1);
        p3.setMax(12);
        p3.setProgress((int) result_ponderate-18);
        
        // GESTIONE PROIEZIONE VOTO LAUREA
        TextView voto_laurea = (TextView)findViewById(R.id.textView10);
        int voto = (int) (result_ponderate / 3 * 11);
        if(n_crediti > 0)
        	voto_laurea.setText(""+getString(R.string.st_minimo)+" "+(voto+minVotoLaurea)+" / 110 "+"- "+getString(R.string.st_massimo)+" "+(voto+maxVotoLaurea)+" / 110 ");
        else
        	voto_laurea.setText(""+getString(R.string.st_no_proiezione)+"");
        
        RatingBar b1 = (RatingBar)findViewById(R.id.ratingBar1);
        b1.setEnabled(false);
        b1.setMax(57);
        if(n_crediti > 0)
        	b1.setProgress(voto + (int)(minVotoLaurea + maxVotoLaurea) / 2 - 57);
        else
        	b1.setProgress(0);
        
        // GESTIONE NUMERO LODI
        TextView numero_lodi = (TextView)findViewById(R.id.textView12);
        int n_lodi = db.numberLode();
        numero_lodi.setText(n_lodi+" "+getString(R.string.st_totale)+" " + db.numberAllExamsOk() +" "+getString(R.string.st_tot_superati)+" ");
        
        ProgressBar p5= (ProgressBar)findViewById(R.id.progressBar5);
        p5.setMax(db.numberAllExamsOk());
        p5.setProgress((int) n_lodi);
        
        
        setFeedback(result_ponderate, voto, db.numberAllExamsOk(), n_tot_esami, db.numberAllCreditsOk(), n_tot_crediti);
        
        db.close();
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_statistiche, menu);
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	Intent intent;
    	switch(item.getItemId()){
    	case R.id.dettagli: // Vai a Dettagli Esame
	    	   intent = new Intent (this, Details.class);
			   startActivity(intent);
 	       break;      
	    case R.id.carriera: // Vai a Carriera
	    	   intent = new Intent(this, Carriera.class);
	    	   startActivity(intent);  
 	       break;             
	    case R.id.home: // Vai alla Home
  	   	   intent = new Intent(this, MainActivity.class);
  	   	   startActivity(intent);  
 	       break;                  
    	}
     return true;
    }

    
   public void showMyPersonalDialog(View view){
	   Cursor cursor=null;
	   ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.listitem, R.id.listItemTextView);
	   
	   ModelDialog = new Dialog(this);
	   
	   ModelDialog.setContentView(R.layout.custom_dialog_best);
	   
	   switch(view.getId()){
	        case R.id.layout7: //lodi
	     	    ModelDialog.setTitle(""+getString(R.string.st_dialog_lode)+"");
	        	break;
	        case R.id.layout5: // crediti
	     	    ModelDialog.setTitle(""+getString(R.string.st_dialog_crediti)+"");
	        	break;
	        case R.id.layout4: //esami	
	     	    ModelDialog.setTitle(""+getString(R.string.st_dialog_superati)+"");
	        	break;
	   }
	   
	   ModelDialog.setCancelable(true);
	   
	   db.open();
	   
	   switch(view.getId()){
       case R.id.layout7: //lodi
    	    cursor = db.personalquery("SELECT * FROM exams WHERE lode > 0 ORDER BY name;");
    	    break;
       case R.id.layout5: // crediti
    	    cursor = db.personalquery("SELECT * FROM exams WHERE vote >= 18 ORDER BY name;");
    	    break;
       case R.id.layout4: //esami	
    	    cursor = db.personalquery("SELECT * FROM exams WHERE vote >= 18 ORDER BY name;");
    	    break;
       }
	   

	   int nameCol = cursor.getColumnIndex("name");
	   if(cursor.moveToFirst())
		   do{
			   nameCol = cursor.getColumnIndex("name");
			   arrayAdapter.add(cursor.getString(nameCol));
		   }while(cursor.moveToNext());
	   else
		   switch(view.getId()){
	       case R.id.layout7: //lodi
	    	    arrayAdapter.add(""+getString(R.string.st_no_lode)+"");
	    	    break;
	       case R.id.layout5: // crediti
	    	    arrayAdapter.add(""+getString(R.string.st_no_crediti)+"");
	    	    break;
	       case R.id.layout4: //esami	
	    	    arrayAdapter.add(""+getString(R.string.st_no_superati)+"");
	    	    break;
	       }
		   
	   ListView listView = (ListView) ModelDialog.findViewById(R.id.lista);
	   listView.setAdapter(arrayAdapter);
	   
	   if(cursor.moveToFirst())
		   listView.setOnItemClickListener(new OnItemClickListener() {
			   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
					ListView listView = (ListView) adapterView;
					ArrayAdapter<String> arrayAdapter = (ArrayAdapter<String>) listView.getAdapter();
					String item = arrayAdapter.getItem(position);
					Intent intent = new Intent (getApplicationContext(), Dettagli_esame.class);
					String pkg = getPackageName();
					intent.putExtra(pkg+".myString", item);
					startActivity(intent);
					}
	   });
		   
		
	   db.close();
		
	   ModelDialog.show();
   }
   
   public void showGrafico(View view){
	   float votoMax=-1, votoMin=130;
	   int i;
       int n_esami;
       String s="", t="";
       
       t=getString(R.string.st_superamento_esami);
       
       switch(view.getId()){
	   case R.id.layout6: 
		   s=getString(R.string.st_proiezione);
		   break;
	   case R.id.layout2: 
		   s=getString(R.string.st_media_aritmetica);
		   break;
	   case R.id.layout3: 
		   s=getString(R.string.st_media_ponderata);
		   break;
	   }
       
	   ModelDialog = new Dialog(this);
	  
	   switch(view.getId()){
       case R.id.layout6: //lodi
    	    ModelDialog.setTitle(""+getString(R.string.st_grafico_laurea)+"");
    	    break;
       case R.id.layout2: // crediti
    	    ModelDialog.setTitle(""+getString(R.string.st_grafico_mediaa)+"");
    	    break;
       case R.id.layout3: //esami	
    	    ModelDialog.setTitle(""+getString(R.string.st_grafico_mediap)+"");
    	    break;
	   }
	   
	   ModelDialog.setContentView(R.layout.grafico);
	   
	   ModelDialog.setCancelable(true);
		
	   ModelDialog.show();

	   XYPlot graph = (XYPlot) ModelDialog.findViewById(R.id.mySimpleXYPlot);

	   db.open();
       n_esami = db.numberOkExams(); 
       db.close();
	   
       if(n_esami>1){
    	   Number[] series1Numbers = setValueGraphic(view.getId());
	       
    	   if(series1Numbers.length > 0){
    		   XYSeries series1 = new SimpleXYSeries(Arrays.asList(series1Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, ""+getString(R.string.st_grafico_intest)+"");
    		   LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.rgb(0, 0, 0), Color.rgb(255, 0, 0), Color.TRANSPARENT); // Linea, puntino, sfondo
    		   graph.addSeries(series1, series1Format);
    		   
    		   
    		   for(i=0; i<series1Numbers.length; i++){
		  			if(series1Numbers[i].intValue() < votoMin)
		  				votoMin = series1Numbers[i].intValue();
		  			if(series1Numbers[i].intValue() > votoMax)
		  				votoMax = series1Numbers[i].intValue();
    		   }

    		   graph.setRangeBottomMin((int)votoMin-1);
    		   graph.setRangeBottomMax((int)votoMin-1);
    		   graph.setRangeTopMax((int)votoMax+1);
    		   graph.setRangeTopMin((int)votoMax+1);
    		   graph.setRangeStep(XYStepMode.INCREMENT_BY_VAL, (votoMax-votoMin+2)/25);
    		   graph.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
    	   }
       }

	   graph.setTicksPerRangeLabel(1);
	   graph.setTicksPerDomainLabel(1);
	   graph.setDomainLabel(t);
	   graph.setRangeLabel(s);
	   graph.getGraphWidget().setMarginTop(10);
	   graph.getGraphWidget().setMarginRight(10);
	   graph.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
	   graph.disableAllMarkup();
   }
   
   public Number[] setValueGraphic(int id){
	   db.open();
       
       int n_esami = db.numberOkExams();
       Number[] array = new Number[n_esami];
	   int letti = 0, somma = 0, i = 0, crediti, somma_crediti = 0;
	   
	   Cursor c = db.personalquery("SELECT * FROM exams WHERE vote >= 18 AND type=0 ORDER BY data;");
	   
	   if(id == R.id.layout2){
		   		if(c.moveToFirst())
		   			do{
		   				letti++;
		   				int nameCol = c.getColumnIndex("vote");
		   				somma += c.getInt(nameCol);
		   				array[i]=(float) somma / letti;
		   				i++;
		   			}while(c.moveToNext());
	   }
	   else if(id == R.id.layout3){
	   		if(c.moveToFirst())
	   			do{
	   				letti++;
	   				int nameCol = c.getColumnIndex("credits");
	   				somma_crediti +=  c.getInt(nameCol);
	   				crediti = c.getInt(nameCol);
	   				nameCol = c.getColumnIndex("vote");
	   				somma += crediti*c.getInt(nameCol);
	   				array[i]=(float) somma  / somma_crediti;
	   				i++;
	   			}while(c.moveToNext());
	   		}
	   		else{
		   		if(c.moveToFirst())
		   			do{
		   				letti++;
		   				int nameCol = c.getColumnIndex("credits");
		   				somma_crediti +=  c.getInt(nameCol);
		   				crediti = c.getInt(nameCol);
		   				nameCol = c.getColumnIndex("vote");
		   				somma += crediti*c.getInt(nameCol);
		   				array[i]=(float) somma  / somma_crediti / 3 * 11 + (minVotoLaurea+maxVotoLaurea)/2;
		   				i++;
		   			}while(c.moveToNext());
		   	}
		   
	   db.close();
	   
       return array;
   }
   
   public void setFeedback(float media, float prev, int esami, int totesami, int crediti, int totcrediti){
	   TextView s = (TextView) findViewById(R.id.feedback);
	   
	   if(esami == 0) s.setText("myLibretto: \""+getString(R.string.st_feed1)+"\" ");
	   else if(esami+5 > totesami) {
		   if(prev > 100) s.setText("myLibretto: \""+getString(R.string.st_feed2)+"\" ");
		   else  s.setText("myLibretto: \""+getString(R.string.st_feed3)+"\" ");
	   }
	   else if(media <= 20) s.setText("myLibretto: \""+getString(R.string.st_feed4)+"\" ");
	   else if(media <= 21) s.setText("myLibretto: \""+getString(R.string.st_feed5)+"\" ");
	   else if(media <= 22) s.setText("myLibretto: \""+getString(R.string.st_feed6)+"\" ");
	   else if(media <= 23) s.setText("myLibretto: \""+getString(R.string.st_feed7)+"\" ");
	   else if(media <= 24) s.setText("myLibretto: \""+getString(R.string.st_feed8)+"\" ");
	   else if(media <= 25) s.setText("myLibretto: \""+getString(R.string.st_feed9)+"\" ");
	   else if(media <= 26) s.setText("myLibretto: \""+getString(R.string.st_feed10)+"\" ");
	   else if(media <= 27) s.setText("myLibretto: \""+getString(R.string.st_feed11)+"\" ");
	   else if(media <= 28) s.setText("myLibretto: \""+getString(R.string.st_feed12)+"\" ");
	   else if(media <= 29) s.setText("myLibretto: \""+getString(R.string.st_feed13)+"\" ");
	   else s.setText("myLibretto: \""+getString(R.string.st_feed4)+"\" ");
   }
}
